﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class ForumPostList : BaseUserControl
    {
        private String BackToDiscussionLocalized = "BackToDiscussion".ToLocalizedString();
        private String onlineLocalized = "online".ToLocalizedString();
        private String awayLocalized = "away".ToLocalizedString();
        private String UnknownLocalized = "Unknown".ToLocalizedString();

        private Int32 _forumTopicId;
        public Int32 ForumCategoryId { get; set; }
        public Int32 ForumTopicId
        {
            get { return this._forumTopicId; }
            set
            {
                this._forumTopicId = value;
                var ThisTopic = ForumTopicDal.GetEntity(value);
                if (ThisTopic == null)
                    throw new HttpException(404, String.Format("This Topic has been deleted: {0}", _forumTopicId));

                var ThisTopicLabel = ThisTopic.LabelForumTopic;
                ForumPostEntityDataSource.WhereParameters["ForumTopicIdParam"].DefaultValue = value.ToString();
                Panel2.GroupingText = String.Format("{0} {1}", "DiscussionSTopic".ToLocalizedString(), ThisTopicLabel);
                ThisMaster.Page.Title = prefixTitle + ThisTopicLabel;
            }
        }
        public Int32 ShowPostId { get; set; }
        public String UserAddressIp { get; set; }
        private Boolean IsTopicUnlocked;
        private Int32 UserRightLevel { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            List<Int32> pollIds;
            ShowOnePoll poll;

            const Int32 CurrentPostListPageSize = 15;

            Int32 PostPageNumber;
            String urlDestination;
            ForumCategory thisCategory;

            if (Page.RouteData.Values["postId"] != null)
                this.ShowPostId = Int32.Parse(Page.RouteData.Values["postId"].ToString());

            if (Page.RouteData.Values["topicId"] != null)
                this.ForumTopicId = Int32.Parse(Page.RouteData.Values["topicId"].ToString());
            else if (this.ShowPostId > 0)
                this.ForumTopicId = ForumTopicDal.GetTopicIdByPostId(this.ShowPostId);

            if (ForumTopicDal.GetEntity(this.ForumTopicId) == null)
                throw new HttpException(404, "This topic don't exists.");
            this.ForumCategoryId = ForumCategoryDal.GetCategoryIdByTopicId(this.ForumTopicId);

            //Vérifier si l'utilisateur à accès à ce message
            this.UserRightLevel = UserAccessDal.UserRightLevel(this.ForumCategoryId, ((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()));
            if (this.UserRightLevel == RightLevel.NoAccess)
                Response.Redirect(String.Format("~/{0}/connexion/?returnurl=~{1}", ThisMaster.Requester.Culture, Request.RawUrl));

            this.IsTopicUnlocked = ForumTopicDal.GetEntity(this.ForumTopicId).IsUnlocked;

            // Chargement des sondages et de leur question
            pollIds = PollDal.GetPollList(this.ForumTopicId);
            if (pollIds.Count > 0)
            {
                foreach (Int32 pollId in pollIds)
                {
                    poll = LoadControl("~/Pages/Polling/ShowOnePoll.ascx") as ShowOnePoll;
                    poll.PollId = pollId;
                    poll.UserIpAddress = ThisMaster.Requester.IpAddress;
                    poll.EditPollButtonClick += this.EditPoll_Click;
                    PollPlaceHolder.Controls.Add(poll);
                }
                ShowPollPanel.Visible = true;
            }

            // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu, ni à la création de sujet
            if (Session["AnonymousID"] == null)
            {
                ReplyHyperLink.NavigateUrl = String.Format("~/{0}/messagedetail/post/{1}/0/", ThisMaster.Requester.Culture, this.ForumTopicId);
                ReplyHyperLink2.NavigateUrl = String.Format("~/{0}/messagedetail/post/{1}/0/", ThisMaster.Requester.Culture, this.ForumTopicId);
                NewTopicHyperLink.Visible = true;
                NewTopicHyperLink.NavigateUrl = String.Format("~/{0}/topicdetail/{1}/0/", ThisMaster.Requester.Culture, this.ForumCategoryId);
                NewTopicHyperLink2.Visible = true;
                NewTopicHyperLink2.NavigateUrl = String.Format("~/{0}/topicdetail/{1}/0/", ThisMaster.Requester.Culture, this.ForumCategoryId);
                UnreadHyperLink.Visible = true;
                UnreadHyperLink2.Visible = true;
            }
            else
            {
                NewTopicHyperLink.Visible = false;
                NewTopicHyperLink2.Visible = false;
                UnreadHyperLink.Visible = false;
                UnreadHyperLink2.Visible = false;
            }

            if (this.ShowPostId > 0)
            {
                if (ForumPostDal.GetEntity(this.ShowPostId) == null)
                    throw new HttpException(404, "This post don't exists.");

                PostPageNumber = ForumPostDal.GetPostIdPageNumber(this.ForumTopicId, this.ShowPostId, CurrentPostListPageSize);

                urlDestination = String.Format("~/{0}/forumpost/{1}/?postpagenumber={2}#bottom", ThisMaster.Requester.Culture, this.ForumTopicId, PostPageNumber.ToString());
                Response.Redirect(urlDestination);
            }

            // Mettre à jour le compteur de "vu le sujet"
            // mettre à jour les posts lus par user non-anonyme
            // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu
            if (Session["AnonymousID"] == null)
            {
                if (ForumPostDal.MarkAsRead(this.ForumTopicId, new Guid(ThisMaster.Requester.Membership.ProviderUserKey.ToString())))
                    ForumTopicDal.IncrementNumberOfRead(this.ForumTopicId);
            }

            thisCategory = ForumCategoryDal.GetEntity(this.ForumCategoryId);

            BackToTopicHyperLink.NavigateUrl = String.Format("~/{0}/topic/bycategory/{1}/?topicpagenumber={2}",
                ThisMaster.Requester.Culture,
                thisCategory.Id.ToString(),
                ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty));
            BackToTopicHyperLink.Text = String.Format("[{0} : {1}]", BackToDiscussionLocalized, thisCategory.LabelForumCategory);

            BackToTopicHyperLink2.NavigateUrl = String.Format("~/{0}/topic/bycategory/{1}/?topicpagenumber={2}",
                ThisMaster.Requester.Culture,
                thisCategory.Id.ToString(),
                ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty));
            BackToTopicHyperLink2.Text = String.Format("[{0} : {1}]", BackToDiscussionLocalized, thisCategory.LabelForumCategory);

            HyperLink1.NavigateUrl = String.Format("~/{0}/forum", ThisMaster.Requester.Culture);
            HyperLink2.NavigateUrl = String.Format("~/{0}/forum", ThisMaster.Requester.Culture);

            HyperLink3.NavigateUrl = String.Format("~/{0}/search", ThisMaster.Requester.Culture);
            HyperLink4.NavigateUrl = String.Format("~/{0}/topic/lastpost", ThisMaster.Requester.Culture);
            HyperLink5.NavigateUrl = String.Format("~/{0}/topic/orphan", ThisMaster.Requester.Culture);
            HyperLink6.NavigateUrl = String.Format("~/{0}/topic/lasttopic", ThisMaster.Requester.Culture);
            HyperLink7.NavigateUrl = String.Format("~/{0}/topic/lastpost", ThisMaster.Requester.Culture);
            HyperLink8.NavigateUrl = String.Format("~/{0}/search", ThisMaster.Requester.Culture);
            HyperLink9.NavigateUrl = String.Format("~/{0}/topic/lasttopic", ThisMaster.Requester.Culture);
            HyperLink10.NavigateUrl = String.Format("~/{0}/topic/orphan", ThisMaster.Requester.Culture);

            UnreadHyperLink.NavigateUrl = String.Format("~/{0}/topic/unread", ThisMaster.Requester.Culture);
            UnreadHyperLink2.NavigateUrl = String.Format("~/{0}/topic/unread", ThisMaster.Requester.Culture);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Boolean IsForumModerator = (UserRightLevel == RightLevel.Moderator);

            ReplyHyperLink.Visible = this.IsTopicUnlocked && (this.UserRightLevel > RightLevel.Reader);
            ReplyHyperLink2.Visible = this.IsTopicUnlocked && (this.UserRightLevel > RightLevel.Reader);

            LockTopicButton.Visible = IsForumModerator && this.IsTopicUnlocked;
            UnlockTopicButton.Visible = IsForumModerator && !this.IsTopicUnlocked;

            LockTopicButton2.Visible = IsForumModerator && this.IsTopicUnlocked;
            UnlockTopicButton2.Visible = IsForumModerator && !this.IsTopicUnlocked;

            if (ThisMaster.Requester.Profile == null ||
    !((ForumTopicDal.GetEntity(this.ForumTopicId).AuthorForumTopic.ToLower() == ThisMaster.Requester.Profile.UserName.ToLower())
    && IsTopicUnlocked))
            {
                properties_HeaderPanel.Visible = false;
                AddPollPanel.Visible = false;
            }
            else
            {
                properties_HeaderPanel.Visible = true;
                AddPollPanel.Visible = true;
            }
        }

        protected void ListView1_OnItemDeleted(object sender, ListViewDeletedEventArgs e)
        {
            Int32 rowcount = ListView1.Items.Count - 1;
            Int32 cesure;
            String urlDestination;

            // Il faut mettre à jour explicitement les compteurs
            // NumberOfMessage, la date, l'auteur et l'id du dernier message, car la Dal n'est pas appelée par la ListView.
            ForumCategoryDal.InitializeCategoryCounter(this.ForumCategoryId);

            if (rowcount <= 0)
            {
                cesure = this.Request.Url.ToString().IndexOf("?postpagenumber=");
                if (cesure > 0)
                {
                    urlDestination = this.Request.Url.ToString().Substring(0, cesure);
                    Response.Redirect(urlDestination);
                }
            }
        }

        protected void ListView1_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var item = e.Item;

            if (item.ItemType == ListViewItemType.DataItem)
            {
                String AuthorName;
                Label CreationDateForumPostLabel;
                UserProfile profile;
                Label Message;

                Gravatar Gravatar1;
                Image Bf3RankImage;
                Label NumberOfForumPostLabel;
                Label LocationLabel;
                Label Bf3GradeLabel;

                MembershipUser AuthorMembership;
                Label MemberSinceLabel;
                Label UserStatusLabel;

                ForumSignature ForumSignature1;

                ForumPost ThisForumPost = null;
                Button btn, btn2, btn3;

                ICustomTypeDescriptor descriptor = item.DataItem as ICustomTypeDescriptor;
                if (descriptor != null)
                {
                    var prop = descriptor.GetProperties()[0];
                    ThisForumPost = (ForumPost)descriptor.GetPropertyOwner(prop);
                }

                btn = item.FindControl("QuoteMessageButton") as Button;
                btn2 = item.FindControl("EditMessageButton") as Button;
                btn3 = item.FindControl("DeleteMessageButton") as Button;

                // Tout le monde peut citer un message
                if (ThisMaster.Requester.Membership != null)
                {
                    btn.Command += new CommandEventHandler(DetailButton_Command);
                }
                else
                {
                    btn.Enabled = false;

                    var btnPrivate = item.FindControl("PrivateMessageButton") as Button;
                    if (btnPrivate != null)
                        btnPrivate.Enabled = false;

                    var btnEmail = item.FindControl("EmailMessageButton") as Button;
                    if (btnEmail != null)
                        btnEmail.Enabled = false;
                }

                // seul l'auteur du message peut l'editer
                if (ThisMaster.Requester.Membership != null && (ThisForumPost.PostMessage.Author.ToLower() == ThisMaster.Requester.Membership.UserName.ToLower()))
                {
                    btn2.Command += new CommandEventHandler(DetailButton_Command);
                }
                else
                {
                    btn2.Enabled = false;
                }

                //un modérateur ou l'auteur peuvent supprimer le message
                if (ThisMaster.Requester.Profile != null && ((UserRightLevel == RightLevel.Moderator) || (ThisForumPost.PostMessage.Author.ToLower() == ThisMaster.Requester.Profile.UserName.ToLower())))
                {
                    btn3.Enabled = true;
                }

                AuthorName = ThisForumPost.PostMessage.Author;
                profile = UserProfile.GetUserProfile(AuthorName);
                AuthorMembership = Membership.GetUser(AuthorName, false);

                Message = item.FindControl("MessageForumPostLabel") as Label;
                if (Message != null)
                    Message.Text = ForumPostDal.AutoLink(ForumPostDal.ReplaceSmiliesTextToImage(Message.Text));

                if (profile != null)
                {
                    Gravatar1 = item.FindControl("Gravatar1") as Gravatar;
                    Gravatar1.Email = profile.UserGravatarEmail;

                    Bf3RankImage = item.FindControl("Bf3RankImage") as Image;
                    Bf3RankImage.ImageUrl = profile.Bf3RankImage;

                    NumberOfForumPostLabel = item.FindControl("NumberOfForumPostLabel") as Label;
                    NumberOfForumPostLabel.Text = profile.NumberOfForumPost.ToString();

                    LocationLabel = item.FindControl("LocationLabel") as Label;
                    LocationLabel.Text = profile.Location;

                    Bf3GradeLabel = item.FindControl("Bf3GradeLabel") as Label;
                    Bf3GradeLabel.Text = profile.Bf3Grade;
                }


                MemberSinceLabel = item.FindControl("MemberSinceLabel") as Label;
                UserStatusLabel = item.FindControl("UserStatusLabel") as Label;

                if (AuthorMembership != null)
                {
                    MemberSinceLabel.Text = AuthorMembership.CreationDate.ToShortDateString();
                    UserStatusLabel.Text = (AuthorMembership.IsOnline) ? onlineLocalized : awayLocalized;
                }
                else
                {
                    MemberSinceLabel.Text = UnknownLocalized;
                    UserStatusLabel.Text = UnknownLocalized;
                }

                CreationDateForumPostLabel = item.FindControl("CreationDateForumPostLabel") as Label;
                if (CreationDateForumPostLabel != null)
                    CreationDateForumPostLabel.Text = DateTime.Parse(CreationDateForumPostLabel.Text).ToUserTimeZone(ThisMaster.Requester.Profile.TimeZone).ToString();

                ForumSignature1 = item.FindControl("ForumSignature1") as ForumSignature;
                ForumSignature1.UpperText = profile.UpperLabelSignature;
                ForumSignature1.ImageUrl = profile.ImageUrlSignature;
                ForumSignature1.NavigateUrl = profile.NavigateUrlSignature;
                ForumSignature1.BottomText = profile.BottomLabelSignature;
            }


        }

        protected void LockTopicButton_Click(object sender, EventArgs e)
        {
            ForumTopicDal.LockEntity(this.ForumTopicId);
            this.IsTopicUnlocked = false;
        }

        protected void UnlockTopicButton_Click(object sender, EventArgs e)
        {
            ForumTopicDal.UnlockEntity(this.ForumTopicId);
            this.IsTopicUnlocked = true;
        }

        protected void DetailButton_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "EditCommand")
            {
                Response.Redirect(String.Format("~/{0}/messagedetail/post/{1}/{2}/", ThisMaster.Requester.Culture, this.ForumTopicId, Int32.Parse(e.CommandArgument.ToString())));
            }

            if (e.CommandName == "QuoteCommand")
            {
                Response.Redirect(String.Format("~/{0}/messagedetail/quote/{1}/{2}/", ThisMaster.Requester.Culture, this.ForumTopicId, Int32.Parse(e.CommandArgument.ToString())));
            }
        }
        protected void AddPollButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            Int32 id = 0;
            Poll pollToUpdate = null;

            List<PollAnswer> answers = new List<PollAnswer>();
            answers.Add(new PollAnswer() { Id = Int32.Parse(Answer1IdLabel.Text), LabelPollAnwser = Answer1TextBox.Text });
            answers.Add(new PollAnswer() { Id = Int32.Parse(Answer2IdLabel.Text), LabelPollAnwser = Answer2TextBox.Text });
            answers.Add(new PollAnswer() { Id = Int32.Parse(Answer3IdLabel.Text), LabelPollAnwser = Answer3TextBox.Text });
            answers.Add(new PollAnswer() { Id = Int32.Parse(Answer4IdLabel.Text), LabelPollAnwser = Answer4TextBox.Text });
            answers.Add(new PollAnswer() { Id = Int32.Parse(Answer5IdLabel.Text), LabelPollAnwser = Answer5TextBox.Text });

            id = Int32.Parse(PollIdLabel.Text);

            pollToUpdate = new Poll()
            {
                Id = id,
                LabelPoll = QuestionTextBox.Text,
                DescriptionPoll = DescriptionTextBox.Text,
                DurationInDays = Int32.Parse(DurationTextBox.Text),
                OrderPoll = 0,
                ForumTopic = new ForumTopic() { Id = this.ForumTopicId }
            };

            if (id == 0)
            {
                id = PollDal.CreatePollAndAnswer(pollToUpdate, answers);

                // mise à jour de l'affichage du panel des sondages
                var poll = LoadControl("~/Pages/Polling/ShowOnePoll.ascx") as ShowOnePoll;
                poll.PollId = id;
                PollPlaceHolder.Controls.Add(poll);
            }
            else
            {
                PollDal.UpdateEntity(pollToUpdate, answers);
            }

            CleanCreatePoll();

            Response.Redirect(this.Request.Url.ToString());
        }
        protected void CleanCreatePoll()
        {
            // remise à zéro des controles de saisie d'ajout d'un sondage
            QuestionTextBox.Text = String.Empty;
            DescriptionTextBox.Text = String.Empty;
            DurationTextBox.Text = "0";

            Answer1IdLabel.Text = "0";
            Answer1TextBox.Text = String.Empty;
            Answer2IdLabel.Text = "0";
            Answer2TextBox.Text = String.Empty;
            Answer3IdLabel.Text = "0";
            Answer3TextBox.Text = String.Empty;
            Answer4IdLabel.Text = "0";
            Answer4TextBox.Text = String.Empty;
            Answer5IdLabel.Text = "0";
            Answer5TextBox.Text = String.Empty;
        }
        protected void EditPoll_Click(object sender, PollItemEventArgs e)
        {
            Poll editingPoll = PollDal.GetEntity(e.PollId);

            PollIdLabel.Text = e.PollId.ToString();
            QuestionTextBox.Text = editingPoll.LabelPoll;
            DescriptionTextBox.Text = editingPoll.DescriptionPoll;
            DurationTextBox.Text = editingPoll.DurationInDays.ToString();

            PollAnswer[] answers = editingPoll.PollAnswer.Take(5).ToArray();
            if (answers.Length > 0)
            {
                Answer1IdLabel.Text = answers[0].Id.ToString();
                Answer1TextBox.Text = answers[0].LabelPollAnwser;
            }
            if (answers.Length > 1)
            {
                Answer2IdLabel.Text = answers[1].Id.ToString();
                Answer2TextBox.Text = answers[1].LabelPollAnwser;
            }
            if (answers.Length > 2)
            {
                Answer3IdLabel.Text = answers[2].Id.ToString();
                Answer3TextBox.Text = answers[2].LabelPollAnwser;
            }
            if (answers.Length > 3)
            {
                Answer4IdLabel.Text = answers[3].Id.ToString();
                Answer4TextBox.Text = answers[3].LabelPollAnwser;
            }
            if (answers.Length > 4)
            {
                Answer5IdLabel.Text = answers[4].Id.ToString();
                Answer5TextBox.Text = answers[4].LabelPollAnwser;
            }

            collapsiblePanel1.Collapsed = false;
            AddPollUpdatePanel.Update();
        }

        protected void CancelPollButton_Click(object sender, EventArgs e)
        {
            CleanCreatePoll();
        }
    }
}
